import qs from "qs";
import { useResponse, useResponseError } from "@/http/useResponse";
import { useEnv } from "@/libs/useEnv";
import { getCurrentLanguage } from "@/libs/useLanguageEnum";

const BASE_URL = useEnv().baseUrl;

export const useFetch = function(data: RequestData): Promise<any> {

  const { url } = data;
  return new Promise((resolve, reject) => {
    if (data.config?.method?.toUpperCase() === "GET" || data.config?.method === undefined) {
      const qsString = qs.stringify(data.data, { indices: true });
      fetch(`${BASE_URL}${url}?${qsString}`, {
        //@ts-ignore
        credentials: "include", mode: "cors", headers: {
          'Language-Code': getCurrentLanguage()
        }
      }).then(res => {
        useResponse(res, resolve, reject);
      }).catch(err => {
        useResponseError(err, reject);
      });
    } else {
      const getContentType = ()=> data.config?.multipart? {}:{"Content-Type": "application/json; charset=UTF-8"};
      const baseUrl = data.baseURL || BASE_URL;
      fetch(baseUrl + url || "", {
        body: data.config?.multipart ? data.data : data.json? JSON.stringify(data.data) : JSON.stringify(data.data),
        ...data.config,
        headers: Object.assign({
          ...getContentType(),
          'Language-Code': getCurrentLanguage(),
        },data.config?.headers),
        credentials: "include",
        mode: "cors", // no-cors, *cors, same-origin
        cache: "no-cache"
      } as RequestInit).then(res => {
        useResponse(res, resolve, reject);
      }).catch(err => {
        useResponseError(err, reject);
      });
    }
  });
};

